package abq2.jic.jic.plugin.other.other.mob.mob;

import kd.bos.algo.DataSet;
import kd.bos.algo.Row;
import kd.bos.data.BusinessDataReader;
import kd.bos.dataentity.entity.DynamicObject;
import kd.bos.dataentity.entity.DynamicObjectCollection;
import kd.bos.dataentity.metadata.clr.DataEntityPropertyCollection;
import kd.bos.entity.property.BasedataProp;
import kd.bos.form.IFormView;
import kd.bos.form.ShowType;
import kd.bos.form.control.Label;
import kd.bos.form.events.*;
import kd.bos.form.plugin.AbstractMobFormPlugin;
import kd.bos.list.BillList;
import kd.bos.list.MobileListShowParameter;
import kd.bos.list.events.CreateListDataProviderListener;
import kd.bos.mvc.list.ListDataProvider;
import kd.bos.mvc.list.QueryBuilderFactory;
import kd.bos.orm.query.QCP;
import kd.bos.orm.query.QFilter;
import kd.bos.servicehelper.QueryServiceHelper;
import kd.bos.servicehelper.user.UserServiceHelper;
import org.json.JSONArray;

import java.util.*;

// 过滤当前用户借书
public class BookMobMainPlugin extends AbstractMobFormPlugin implements BeforeBindDataListener {

    private static String BOOK_STATUS = "status_key";

    @Override
    public void initialize() {
        super.initialize();
        BillList billList = getControl("kdec_billlistap");
        billList.addBeforeBindDataListener(this);
    }

    @Override
    public void registerListener(EventObject e) {
        super.registerListener(e);
        addClickListeners("kdec_activity");
    }

    @Override
    public void click(EventObject evt) {
        super.click(evt);
        MobileListShowParameter mobileListShowParameter = new MobileListShowParameter();
        mobileListShowParameter.setBillFormId("kdec_borrowbook");
        mobileListShowParameter.setFormId("bos_moblist");
        mobileListShowParameter.getOpenStyle().setShowType(ShowType.Floating);


        //获取最外层根页面的View对象
        IFormView mainView = getView().getParentView();
        //绑定弹出列表到根页面
        mainView.showForm(mobileListShowParameter);
        this.getView().sendFormAction(mainView);

    }

    @Override
    public void beforeBindData(BeforeBindDataEvent beforeBindDataEvent) {
        BillList billList = this.getControl("kdec_billlistap");
        billList.addCreateListDataProviderListener(new CreateListDataProviderListener() {
            @Override
            public void createListDataProvider(BeforeCreateListDataProviderArgs args) {
                args.setListDataProvider(new MobBookListDataProvider());
            }
        });
    }

    @Override
    public void afterBindData(EventObject e) {
        this.setListUnitStyle();
        super.afterBindData(e);
    }

    private void setListUnitStyle() {
        JSONArray statusList = new JSONArray(getPageCache().get(BOOK_STATUS));
        BillList billList = getView().getControl("kdec_billlistap");
        for (int i = 0; i < statusList.length(); i++) {
            Map<String, Object> root = new HashMap<>();
            Map<String, Object> map = new HashMap<>();
            if (statusList.get(i).equals("C")) {
                map.put("fc", "#fb2323");
            } else {
                map.put("fc", "#40bd6e");
            }
            root.put("kdec_billstatusfield", map);
            billList.setCustomProperties("kdec_billlistap", i, root);
        }

        Label label = getControl("kdec_labelap1");
        label.setText("（已借阅" + statusList.length() + "本）");
    }

    public class MobBookListDataProvider extends ListDataProvider {
        @Override
        public DynamicObjectCollection getData(int start, int limit) {
            setQueryBuilder(QueryBuilderFactory.createQueryBuilder(this, start, limit, false));

            BillList billList = getControl("kdec_billlistap");
            // 构造过滤条件
            DynamicObject cUser = UserServiceHelper.getCurrentUser("");
            QFilter userQFilter = new QFilter("kdec_userfield", QCP.equals, cUser.get("id"));

            DataSet borrowDataSet = QueryServiceHelper.queryDataSet(getClass().getName(),
                    "kdec_borrowbook", "id, billno, billstatus, kdec_detail.id, kdec_detail.kdec_bd_book, kdec_detail.kdec_borrow_date, kdec_detail.kdec_billstatusfield", userQFilter.toArray(), "kdec_detail.kdec_borrow_date desc");

            String[] fields = getQueryBuilder().getSelectFields().split(",");

            // 构造准备缓存的状态
            JSONArray statusList = new JSONArray();
            // 构造借书单的DynamicObjectCollection
            DynamicObjectCollection collection = new DynamicObjectCollection(getQueryBuilder().getReturnEntityType(), null);
            while (borrowDataSet.hasNext()) {
                Row row = borrowDataSet.next();

                statusList.put(row.get("kdec_detail.kdec_billstatusfield").toString());

                DynamicObject dynamicObject = collection.addNew();
                DataEntityPropertyCollection dataEntityProperties = dynamicObject.getDynamicObjectType().getProperties();
                for (String field : fields) {
                    if (dataEntityProperties.get(field) instanceof BasedataProp) {
                        if (field.equals("kdec_detail.kdec_bd_book")) {
                            dynamicObject.set("kdec_bd_book_id", row.get(field));
                        }
                    } else {
                        dynamicObject.set(field, row.get(field));
                    }
                }
            }
            borrowDataSet.close();

            getPageCache().put(BOOK_STATUS, statusList.toString());

            // 加载基础资料
            BusinessDataReader.loadRefence(
                    collection.toArray(new DynamicObject[collection.size()]),
                    collection.getDynamicObjectType());
            return collection;

        }
    }


}
